package com.net.common.enums.spring;

import com.net.common.enums.base.IntEnum;
import com.net.common.enums.base.StringEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * @author  on 2017/6/8.
 * Spring enum绑定到对象上的factory
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public class StringEnumConverterFactory implements ConverterFactory<String, Enum> {

    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        if (IntEnum.class.isAssignableFrom(targetType)) {
            return new StringToIntEnum(targetType);
        } else if (StringEnum.class.isAssignableFrom(targetType)) {
            return new StringToStringEnum(targetType);
        } else {
            return new StringToEnum(targetType);
        }
    }

    private static class StringToEnum<T extends Enum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            if (source.length() == 0) {
                // It's an empty enum identifier: reset the enum value to null.
                return null;
            }
            return (T) Enum.valueOf(this.enumType, source.trim());
        }
    }

    private static class StringToIntEnum<T extends Enum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToIntEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            IntEnum[] objs = (IntEnum[]) enumType.getEnumConstants();
            for (IntEnum em : objs) {
                if ((("" + em.getValue()).equals(source))) {
                    return (T) em;
                }
            }
            return null;
        }
    }

    private static class StringToStringEnum<T extends Enum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToStringEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            StringEnum[] objs = (StringEnum[]) enumType.getEnumConstants();
            for (StringEnum em : objs) {
                if (em.getValue().equals(source)) {
                    return (T) em;
                }
            }
            return null;
        }
    }

}
